package edu.cicese.alz.swing;

import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import java.awt.Color;

/**
 * Created by: Eduardo Quintana Contreras
 * Date: 25/06/12
 * Time: 06:16 PM
 */
public class IntensityChangeListener implements DocumentListener {

	JNonEmptyTextField textField1, textFieldDuplicate;
	JNonEmptyTextField[] textFields;

	public IntensityChangeListener(JNonEmptyTextField textField1, JNonEmptyTextField textFieldDuplicate,
	                               JNonEmptyTextField[] textFields) {
		this.textField1 = textField1;
		this.textFieldDuplicate = textFieldDuplicate;
		this.textFields = textFields;
	}

	public void insertUpdate(DocumentEvent e) {
		copy();
	}

	public void removeUpdate(DocumentEvent e) {
		copy();
	}

	public void changedUpdate(DocumentEvent e) {
		copy();
	}

	public void copy() {
		try {
			Integer.parseInt(textField1.getText());
			textFieldDuplicate.setText((Integer.valueOf(textField1.getText()) - 1) + "");
			textField1.setBorder(SwingUtil.borderTextField);
			textField1.setBackground(Color.WHITE);
			int threshold = 0;
			for (JNonEmptyTextField textField : textFields) {
				if (!textField.getText().equals("")) {
					int number = Integer.parseInt(textField.getText());
					if (number > threshold) {
						SwingUtil.setTextFieldError(textField, false);
						threshold = number;
					} else {
						SwingUtil.setTextFieldError(textField, true);
					}
				}
			}
		} catch (NumberFormatException nfe) {
			SwingUtil.setTextFieldError(textField1, true);
		}
	}
}
